import { readYaml } from './tool';
import { dirname, join } from 'path';
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
import prompts from 'prompts';
import { green, yellow } from 'kolorist';

declare global {
  var cfg: {
    appID: string;
    token: string;
    intents?: [];
    sandbox?: boolean;
  };
}
export async function check(): Promise<any> {
  const file = join(process.cwd(), './config/config.yaml');
  const config = readYaml(file);

  if (
    (config ?? '') !== '' &&
    (config.account ?? '') !== '' &&
    (config.account.appID ?? '') !== '' &&
    (config.account.token ?? '') !== ''
  ) {
    global.cfg = config.account;
  } else {
    console.log(yellow('请按提示输入，生成配置文件config.yaml，输入错误【Ctrl+c】结束重来'));
    console.log(
      yellow(
        '注册机器人：https://q.qq.com ，教程：https://support.qq.com/products/396585/faqs-more/'
      )
    );
    let result: prompts.Answers<'appID' | 'token'>;
    result = await prompts([
      {
        type: 'text',
        name: 'appID',
        message: green('请输入appID: '),
        validate: value => (value !== '' && typeof value === 'string' ? true : '请输入appID')
      },
      {
        type: 'text',
        name: 'token',
        message: green('请输入token: '),
        validate: value => (value !== '' && typeof value === 'string' ? true : '请输入token')
      }
    ]);

    const { appID, token } = result;
    if (!appID || !token) {
      process.exit();
    }
    let str = readFileSync(join(__dirname, '../../config/config_default.yaml'), 'utf-8');

    str = str.replace(/appID(.*)''/g, `appID: '${appID}'`);
    str = str.replace(/token(.*)''/g, `token: '${token}'`);
    // 以递归的方式创建目录
    mkdirSync(dirname(join(process.cwd(), './config/config.yaml')), { recursive: true });

    writeFileSync(join(process.cwd(), './config/config.yaml'), str);
    console.log(green('生成配置文件成功\n其他配置请打开config/config.yaml修改'));
    const file = join(process.cwd(), './config/config.yaml');
    const config = readYaml(file);
    global.cfg = config.account;
  }
}
